from rest_framework import serializers
from orders.models import OrderModel, OrderDetailModel
from django_redis import get_redis_connection
from coupon.models import CouponManage
from django.db import transaction
from doctors.models import DoctorModel
from dingxiang.utils import constants
import datetime
import traceback

class OrderSerializer(serializers.ModelSerializer):
    user_coupon_id = serializers.IntegerField(write_only=True, default=None)
    doctor_id = serializers.IntegerField(write_only=True, default=None)
    discount_name = serializers.CharField(max_length=50,write_only=True,default=None)
    class Meta:
        model = OrderModel
        fields = ['id', 'pay_type','user_coupon_id','doctor_id','discount_name']
        extra_kwargs = {
            "pay_type":{'write_only': True}
        }

        # 新增数据
    def create(self, validated_data):
        # 往订单表中添加新订单
        # 获取用户，上下文context获取
        user = self.context['request'].user
        print('user',user)
        user_id = user.id
        print('user_id',user_id)
        # 获取用户使用的优惠券
        user_coupon_id = validated_data.get('user_coupon_id',None)
        doctor_id = validated_data.get('doctor_id',None)

        print('--------------------调试输入-----------------------------')
        if doctor_id is None:
            raise serializers.ValidationError("医生 ID 不能为空")
        print(f"doctor_id: {doctor_id}")
        print('---------------------------调试输出----------------------------------')

        user_coupon1 = None
        print('user_coupon_id444444444444444444444444444444444',user_coupon_id)
        if user_coupon_id is not None:
            user_coupon1 = CouponManage.objects.filter(id=user_coupon_id,user_id=user_id).first()
            print('666666666666666666666666666666666有优惠券',user_coupon1)
        else:
            print('99999999999999999999999999999999没有优惠券')

        # 创建订单操作  开启数据库事务
        with transaction.atomic():
            # 创建事务的还原点

            t1 = transaction.savepoint()
            try:
                print('开始创建订单')
                orders = OrderModel.objects.create(
                    name='丁香医生咨询购买下单',
                    user_id=user_id,
                    # 生产订单号
                    order_number=datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(("%08d" % user_id)),
                    pay_type=validated_data.get('pay_type'))
                # 订单记录表创建完成，获取课程，生成订单详情数据，并外键增加
                # 获取最优的优惠券
                # 订单总价  优惠活动以后得总价
                # 医生总价：实付价格
                print('订单创建成功',orders)
                # 获取当前的医生
                # filter返回的是一个queryset集，没法拿里面的字段，只能用get
                # doctor_objs = DoctorModel.objects.filter(id=doctor_id)
                doctor_objs = DoctorModel.objects.get(id=doctor_id)
                print('获取当前的医生',doctor_objs)


                total_discount_price = 0



                detail_list = []
                discount_name = validated_data.get('discount_name',"通用类型")
                print('获取优惠券名称',discount_name)
                # 计算最终优惠价格
                if user_coupon1:
                    print('有优惠券',user_coupon1)
                    sale = user_coupon1.coupon.sale[1:] # 去掉百分号
                    if user_coupon1.coupon.discount == 1:
                        total_discount_price = float(sale)
                    elif user_coupon1.coupon.discount == 2:
                        total_discount_price = float(doctor_objs.consultation_price)*(1-float(sale))

                orders.total_price = doctor_objs.consultation_price
                orders.real_price = float(doctor_objs.consultation_price) - total_discount_price
                orders.save()
                detail_list.append(OrderDetailModel(
                    order=orders,
                    doctor=doctor_objs,
                    price=doctor_objs.consultation_price,
                    real_price=float(doctor_objs.consultation_price)-total_discount_price,
                    discount_name=discount_name
                    ))

                # 一次性往数据库中添加商品详情列表对象
                OrderDetailModel.objects.bulk_create(detail_list)


                # 如果有优惠券，则更新优惠券状态为已使用

                if user_coupon1:
                    # 将优惠券从redis中删除
                    # 将优惠券信息绑定到订单中
                    user_coupon1.order = orders
                    user_coupon1.use_status = constants.COUPON_USE_STATUS_USED
                    user_coupon1.use_time = datetime.datetime.now()
                    user_coupon1.save()
                    redis = get_redis_connection("coupon")
                    redis.delete(f"{user_id}:{user_coupon_id}")

                return orders
            except Exception as e:
                print('当前订单生成失败....')
                print(e)
                # 打印异常的类型和描述
                print(f'An error occurred:{type(e).__name__}-{e}')
                # 打印异常的堆栈跟踪信息
                traceback.print_exc()
                # 回滚到事务的还原点
                transaction.savepoint_rollback(t1)
                raise serializers.ValidationError(detail='订单生成失败，请稍后再试...',code='order_fail')



class OrderDetailSerializer(serializers.ModelSerializer):
    doctor_id = serializers.IntegerField(source='doctor.id')
    doctor_name = serializers.CharField(source='doctor.name')
    doctor_avatar = serializers.CharField(source='doctor.avatar')
    class Meta:
        model = OrderDetailModel
        fields = ['id','price','real_price','doctor_id','doctor_name','doctor_avatar','discount_name']


class OrderListModelSerializer(serializers.ModelSerializer):
    order_detail = OrderDetailSerializer(many=True)
    class Meta:
        model = OrderModel
        fields = ['id','total_price','real_price','order_number','order_status','pay_type','order_detail','order_desc','pay_time','created_time','coupon']
